package news.action;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import news.biz.NewsBiz;
import news.biz.TypesBiz;
import news.entity.News;
import news.entity.Types;
import news.entity.Users;

/**
 * 新闻类型的action
 */
@WebServlet("/news.do")
public class NewsAction extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private NewsBiz newsBiz;
	private TypesBiz typesBiz;
	private HttpSession session;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		// 实例化session对象
		session = request.getSession();
		// 获取op参数
		String op = request.getParameter("op");
		// 获得方法返回的页面名
		String url = "";
		switch ( op ) {
			case "add":
				url = addNews(request,response);
				break;
			case "jump":
				url = jumpPushPages(request,response);
				break;
			default:
				url = "error.jsp";
				break;
		}
		
		// 进行统一跳转
		request.getRequestDispatcher("WEB-INF/pages/" + url).forward(request, response);
	}

	/**
	 * 添加新闻
	 * @param request
	 * @param response
	 * @return
	 */
	private String addNews(HttpServletRequest request, HttpServletResponse response) {
		News news = new News();
		
		news.setTitle(request.getParameter("title"));
		news.setContent(request.getParameter("content"));
		news.setRecommended(Integer.parseInt(request.getParameter("hot")));
		news.setKeywords(request.getParameter("keywords"));
		// 类型
		Types types = new Types();
		types.setTypeid(Integer.parseInt(request.getParameter("types")));
		
		news.setType(types);
		
		news.setUser( (Users)session.getAttribute("user") );
		
		boolean flag = newsBiz().addNews(news);
		return "manage.jsp?include=welcome.jsp";
	}

	/**
	 * 跳转到新闻添加页面
	 * @param request
	 * @param response
	 * @return
	 */
	private String jumpPushPages(HttpServletRequest request, HttpServletResponse response) {
		List< Types > listTyes = typesBiz().queryAllTypes();
		request.setAttribute("typesList", listTyes);
		return "manage.jsp?include=pushNews.jsp";
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	/**
	 * 初始化新闻业务逻辑类
	 * @return
	 */
	public NewsBiz newsBiz() {
		if ( newsBiz == null ) {
			newsBiz = new NewsBiz();
		}
		return newsBiz;
	}
	
	public TypesBiz typesBiz() {
		if ( typesBiz == null ) {
			typesBiz = new TypesBiz();
		}
		return typesBiz;
	}

}
